<?php

class ReportsController extends AppController
{
	public $name = 'Reports';
	public $uses = array('Report', 'Testing', 'Operation', 'Reporting');
	public $helpers = array('Html', 'Form' );
	protected $po_domain = '';
	protected $url_part = 'tools';

	function beforeFilter()
	{
		parent::beforeFilter();

		$this->modelName = 'Report';
		$this->po_domain = Inflector::underscore($this->name);
		$this->url_part  = 'tools';
		$this->set('po_domain', $this->po_domain);
		$this->set('url_part',  $this->url_part);
		$this->set('modelName', $this->modelName);
		$this->set('PKName',    $this->{$this->modelName}->primaryKey);
	    Auth::Access('active');
	}

	function change_prices($id = null)
	{
	    Auth::Access('admin');
		$modelName = $this->modelName;
		$PKName    = $this->{$modelName}->primaryKey;
		$po_domain = $this->po_domain;
		$url_part  = $this->url_part;

		$this->pageTitle = strip_tags(__d($po_domain, 'details_title', true));

	    if (isset($this->params['id'])) {
	        $id = $this->params['id'];
	    }

	    $this->{$modelName}->rel();
        $tmp = $this->{$modelName}->read(null, $id);

		if (! is_array($tmp) || !count($tmp)) {
			$this->msgError(__d($po_domain, 'absent', true), @$error_code);
			$this->redirect("/{$url_part}/", null, true);
			exit();
		}

		////// MENU ///////////////////////

	    $ancestors_menu =& $this->MainMenu->findItem("/{$url_part}/");
	    $this->MainMenu->setActive($ancestors_menu);

		///////////////////////////////////

		$submit = !empty($this->data);
		if (! $this->{$modelName}->allowUpdate($tmp[$modelName])) {
		    $this->data = array($modelName => array());
		}
		foreach ($tmp as $_modelName => $_modelData) {
            if ($_modelName !== $modelName) {
    			$this->data[$_modelName] = $tmp[$_modelName];
            } else {
        		$this->data[$modelName] = am($tmp[$modelName], $this->data[$modelName]);
            }
		}

		if ($this->{$modelName}->allowUpdate($tmp[$modelName]) && $submit) {
			$error_msg = '';
			$success_msg = __d($po_domain, 'changed', true);
            if (empty($error_msg)) {
				if ($this->{$modelName}->save($this->data)) {

				} elseif (!empty($this->{$modelName}->validationErrors)) {
					$error_msg = __d(null, 'Data are incorrectly entered.', true).' '.__d(null, 'Try again.', true);
				} else {
	    		    $error_msg = __d(null, 'There was an internal error.', true).' '.__d(null, 'Try later.', true);
				}
            }
			if (empty($error_msg)) {
			    $this->msgNotice($success_msg);
			    $this->redirect("/{$url_part}/", null, true);
			    exit();
			} else {
			    $this->msgError($error_msg, @$error_code);
			}
		}

		$this->data[$modelName]['__allows']['update'] = $this->{$modelName}->allowUpdate($tmp[$modelName]);
		$this->data[$modelName]['__allows']['delete'] = $this->{$modelName}->allowDelete($tmp[$modelName]);
	}

	function consolidate_create()
	{
		$this->url_part = Auth::o()->is('admin') ? "candidates" : "reports";
		$this->set('url_part', $this->url_part);

	    Auth::Access('admin | REPORTS');
		$modelName = $this->modelName;
		$po_domain = $this->po_domain;
		$url_part  = $this->url_part;

		$this->pageTitle = __d($po_domain, 'creation_consolidate_report_title', true);

		$submit = !empty($this->data);

		$mode = 'normal';
		$client_id = null;
		if (Auth::o()->is('admin')) {
            if (isset($this->params['client_id'])) {
                $Client =& $this->{$modelName}->getModel('Client'); /* @var $Client Client */
                $Client->rel();
                $client = $Client->read(null, $this->params['client_id']);
                if (empty($client[$Client->name][$Client->primaryKey])) {
                    $this->error(404);
                } else {
                    $client_id = $this->params['client_id'];
                }
            } else {
                $mode = 'select_client';
            }
		} else {
		    $auth_data = Auth::o()->data();
		    $client_id = $auth_data['client_id'];
		}

		$this->set('mode', $mode);
		$this->set('client_id', $client_id);

		switch ($mode) {

	    case "select_client":
            $this->_select_client();
            break;

	    case "normal":
            $this->_consolidate_create($client_id);
            break;
		}
	}

	protected function _select_client()
	{
		$this->pageTitle = __d("reports", 'select_client_for_consolidate_report_creation_title', true);

		$Client =& $this->{$this->modelName}->getModel("Client"); /* @var $Client Client */
		$this->modelName = $Client->name;
		$modelName = $this->modelName;
		$this->set("modelName", $modelName);

		$PKName = $Client->primaryKey;
		$this->set('PKName', $PKName);

		$this->po_domain = "clients";
		$po_domain = $this->po_domain;
		$this->set("po_domain", $po_domain);

		$url_part  = $this->url_part;

		vendor('contingencies');
		vendor('order_html');
		vendor('pagination_html');
		vendor('page_of_data');

		$contingencies = new Contingencies();
        $contingencies->model =& $Client;
        $contingencies->expects = 'Tests';

        $appearence = new OrderHTML();
        $appearence->orderFields = array(
            'name' => "`{$modelName}`.`name`",
        );
        $appearence->defaultOrder = Order::parseString('name');
        $appearence->processParams();

        $pagination = new PaginationHTML();
        $pagination->defaultLimit = 20;
        $pagination->processParams();

        $list = new PageOfData($contingencies, $appearence, $pagination);

		$this->set("list", $list);
		$this->set('tools_list', $Client->getModel('Test')->generateList());
	}

	protected function _consolidate_create($client_id)
	{
		$modelName = $this->modelName;
		$po_domain = $this->po_domain;
		$url_part  = $this->url_part;

		$this->pageTitle = __d($po_domain, 'creation_consolidate_report_title', true);

		$submit = !empty($this->data);

		if ($submit) {

			$error_code = null;
			$error_msg = '';
			$notice_msg = null;
			$success_msg = __d($po_domain, 'Report has been generated', true);

            $fields = array(
                "test_id" => null,
                "report_id" => null,
                "norm_id" => null,
                "testing_id" => array(),
            );

			/**
			 * Считывание необходимых полей
			 */
			$fields["test_id"] = isset($this->data[$modelName]['test_id']) ? intval(trim($this->data[$modelName]['test_id'])) : null;
			$fields["report_id"] = isset($this->data[$modelName]['report_id']) ? intval(trim($this->data[$modelName]['report_id'])) : null;
			$fields["norm_id"] = isset($this->data[$modelName]['norm_id']) ? intval(trim($this->data[$modelName]['norm_id'])) : null;
			/**
			 * Считывание testing_id
			 */
			$testings_str = isset($this->data[$modelName]['testing_id']) ? $this->data[$modelName]['testing_id'] : "";
            $tmp_testings = explode(",", $testings_str);
            if (! empty($tmp_testings)) {
                foreach ($tmp_testings as $tmp_testing_id) {
                    $fields["testing_id"][intval(trim($tmp_testing_id))] = true;
                }
                if (! empty($fields["testing_id"])) {
                    $fields["testing_id"] = array_keys($fields["testing_id"]);
                }
            }
            $this->data[$modelName]['testing_id'] = implode(",", $fields["testing_id"]);

            if (empty($fields["test_id"]) || empty($fields["report_id"]) || empty($fields["norm_id"]) || empty($fields["testing_id"])) {
				$error_msg = __d(null, 'Data are incorrectly entered.', true).' '.__d(null, 'Try again.', true);
            }
            $bad_testings_num = 0;

            if (empty($error_msg)) {
        		try
        		{
        			$this->Operation->generateConsReport($client_id, $fields["testing_id"], $fields["test_id"], $fields["report_id"], $fields["norm_id"], array("bad_testings_num" => &$bad_testings_num));
        	    }
        	    catch (ArgException $e)
        	    {
                    $error_code = $e->getCode();
        	    	$error_msg = __d(null, 'Data are incorrectly entered.', true).' '.__d(null, 'Try again.', true);
        	    }
        		catch (Exception $e)
        		{
                    $error_code = $e->getCode();
        		    if ($error_code == 1002) {
        		        $error_code = null;
            		    $error_msg = __d('passes', 'Insufficient balance'.(Auth::o()->is('admin') ? "_admin" : ""), true);
        		    } elseif ($error_code == 1029) {
        		        $error_msg = __d("validation", "Must be at least two candidates", true);
        		    } else {
            		    $error_msg = __d(null, 'There was an internal error.', true).' '.__d(null, 'Try later.', true);
        		    }
        		}
            }

			if (empty($error_msg)) {
                $Reporting = $this->{$modelName}->getModel('Reporting'); /* @var $Reporting Reporting */
            	$Reporting->rel();
            	$result = $Reporting->find(null, null, "`{$Reporting->name}`.`{$Reporting->primaryKey}` DESC");
        		$this->Session->write('created_cons_reporting_id', $result[$Reporting->name][$Reporting->primaryKey]);

        		if ($bad_testings_num) {
                    $notice_msg = $bad_testings_num." ".__d("candidates", "candidate_ignore_plurar_".plurar_mode_ru($bad_testings_num), true);
        		}
        		if ($notice_msg) {
        			$this->msgWarning($success_msg, $notice_msg);
        		} else {
        			$this->msgNotice($success_msg);
        		}
        		$redirect_url = array('action'=>'consolidate_list');
        		if (Auth::o()->is('admin')) {
        		    $redirect_url['client_id'] = $client_id;
        		}
    			$this->redirect($redirect_url, null, true);
    			exit();
			} else {
			    $this->msgError($error_msg, @$error_code);
			}

		}

		$this->set('tests_list', $this->{$modelName}->getModel('Test')->getForConsReports());
	}

	function consolidate_list()
	{
	    Auth::Access('admin | REPORTS');
	    $modelName = $this->modelName;
		$PKName    = $this->{$modelName}->primaryKey;
		$po_domain = $this->po_domain;
		$url_part  = $this->url_part;
		$this->set('url_part', $url_part);

		$this->pageTitle = strip_tags(__d($po_domain, 'consolidate_reportings_title', true));

		$client_id = null;
		if (Auth::o()->is('admin')) {
            if (isset($this->params['client_id'])) {
                $Client =& $this->{$modelName}->getModel('Client'); /* @var $Client Client */
                $Client->rel();
                $client = $Client->read(null, $this->params['client_id']);
                if (empty($client[$Client->name][$Client->primaryKey])) {
                    $this->error(404);
                } else {
                    $client_id = $this->params['client_id'];
                }
            }
		} else {
		    $auth_data = Auth::o()->data();
		    $client_id = $auth_data['client_id'];
		}

		$this->set('client_id', $client_id);

		vendor('contingencies');
		vendor('order_html');
		vendor('pagination_html');
		vendor('page_of_data');

		$contingencies = new Contingencies();
        $contingencies->model =& $this->Reporting;
        if (Auth::o()->is('admin')) {
            $contingencies->expects = 'Client | Report';
        } else {
            $contingencies->expects = 'Report';
        }

		$conds = array();
		$conds[]["`{$modelName}`.`type`"] = 'CONSOLIDATED';
		if (isset($client_id)) {
            $conds[]["`Reporting`.`client_id`"] = $client_id;
		}
		$contingencies->conditions =& $conds;

        $appearence = new OrderHTML();
        $appearence->orderFields = array(
            'id' => "`Reporting`.`id`",
            'date' => "`Reporting`.`date`",
            'report' => "`Report`.`name`",
        );
        if (Auth::o()->is('admin')) {
            $appearence->orderFields["client"] = "`Client`.`name`";
        }

        $appearence->defaultOrder = Order::parseString('date');
        $appearence->processParams();

        $pagination = new PaginationHTML();
        $pagination->defaultLimit = 20;
        $pagination->defaultPage = Pagination::pageLast;
        $pagination->processParams();

        $list = new PageOfData($contingencies, $appearence, $pagination);

		$this->set('list', $list);

		if ($active_reporting = $this->Session->read('created_cons_reporting_id')) {
    		$this->Session->delete('created_cons_reporting_id');
    		$this->set('active_reporting_id', $active_reporting);
		}
	}

	function download($id = null)
	{
		Auth::Access('admin | REPORTS');
	    $modelName = $this->modelName;
		$PKName    = $this->{$modelName}->primaryKey;
		$po_domain = $this->po_domain;
		$url_part  = Auth::o()->is('admin') ? $this->url_part : 'reports';

		$this->set('url_part', $url_part);

		$reporting_id = $id;

        $conds = array();
	    $tmp = $this->{$modelName}->find($conds);

        $Reporting = $this->{$modelName}->getModel('Reporting'); /* @var $Reporting Reporting */

        $Reporting->rel('Blob | Testing | Report | Testing.Test');
        $reporting = $Reporting->read(null, $reporting_id);
        if (empty($reporting['Reporting']) || empty($reporting['Blob'])) {
                $this->msgError(__d($po_domain, 'absent_reporting', true), @$error_code);
                $this->redirect("/{$url_part}/", null, true);
                exit();
        }

        $filename = "Report ".$reporting['Report']['name']." ".$reporting['Reporting']['id'].".pdf";
        nodebug();

        $PDF = $reporting['Blob']['data'];

    	header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Content-Type: application/pdf; name=\"{$filename}\"");
		header("Content-Length: ".strlen($PDF));
        header("Content-Disposition: attachment; filename=\"{$filename}\"");

        exit($PDF);
	}
}

?>